/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.siscoh.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.siscoh.model.bean.EspecificacaoBean;
import org.siscoh.model.bean.EspecificacaoItemBean;
import org.siscoh.model.bean.ItemBean;
import org.siscoh.model.bean.UsuarioBean;
import org.siscoh.model.dao.EspecificacaoDao;
import org.siscoh.model.dao.ItemDao;
import org.siscoh.model.dao.UsuarioDao;

/**
 *
 * @author israel
 */
@WebServlet(name = "AjaxController", urlPatterns = {"/AjaxController"})
public class AjaxController extends HttpServlet {

    private static final int REQUEST_ESPEC_FROM_CAT = 1;
    private static final int REQUEST_PECAS_SEARCH = 2;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String acaoStr = request.getParameter("action");
        int acao;

        if (acaoStr != null) {
            acao = Integer.parseInt(acaoStr);
        } else {
            return;
        }


        PrintWriter out = response.getWriter();
        try {

            switch (acao) {
                case REQUEST_ESPEC_FROM_CAT:

                    especFromCategoria(request, out);

                    break;

                case REQUEST_PECAS_SEARCH:

                    pecasSearch(request, out);
                    
                    break;
            }
        } finally {
            out.close();
        }
    }
    
    private void pecasSearch(HttpServletRequest request, PrintWriter out)
    {
        String login, senha;
        
        int permissao = 0;
        
        login = request.getParameter("login");
        senha = request.getParameter("senha");
        
        if(!(login == null || senha == null || login.equals("") || senha.equals("")))
        {
            permissao = verificarLogin(login, senha);
        }
        
        long categId;
        String input;
        
        input = request.getParameter("input");
        categId = Long.parseLong(request.getParameter("categoria"));
        
        ItemBean []itens = new ItemDao(false).searchItens(categId, input);
        
        String html = "";
        
        for(int i = 0; i < itens.length; i++)
        {
            html += parsePecaToHtml(itens[i]);
        }
        
        System.out.println(html.replace("</tr>", "</tr>\n"));
        out.println(html);
    }

    private void especFromCategoria(HttpServletRequest request, PrintWriter out) {
        int idCategoria;

        String categoriaStr = request.getParameter("categoria");

        if (categoriaStr == null || categoriaStr.equals("")) {
            return;
        }

        idCategoria = Integer.parseInt(categoriaStr);

        EspecificacaoDao espDao = new EspecificacaoDao();
        ArrayList<EspecificacaoBean> espList = espDao.selectByCategoria(idCategoria);

        String html = "";

        for (EspecificacaoBean eb : espList) {
            html += parseEspecificacaoToHTML(eb);
        }

        out.println(html);
    }

    private int verificarLogin(String login, String senha) {
        UsuarioBean ub = new UsuarioDao().verificarLogin(login, senha);

        if (ub == null) {
            return 0;
        }

        return (ub.isAdministrador() ? 2 : 1);
    }
    
    private String parsePecaToHtml(ItemBean pb)
    {
        String html = "<tr><td><strong>Código:</strong>"+pb.getId()+
                "</td><td><strong>Nome:</strong>"+pb.getNome()+"</td>"
                + "<td><strong>Categoria:</strong>"+pb.getCategoria().getNome()+"</td></tr>";
        
        ArrayList<EspecificacaoItemBean> espAL = pb.getEspecificacoesList();
        
        if(espAL == null || espAL.size() == 0)
            return html;
        
        int qtdEsp = espAL.size();
        
        html += "<tr><td colspan='3' align='center'><strong>Especificações</strong></td></tr>";
        
        if(qtdEsp > 0)
            html += "<tr><td colspan=\"3\">";
        
        int i;
        
        for(i = 0; i < qtdEsp-1; i++)
        {
            EspecificacaoItemBean espItem = espAL.get(i);
            
            html += espItem.getValor()+"; ";
        }
        
        if(qtdEsp > 0)
        {
            html += espAL.get(i).getValor()+"</td></tr>";
        }
        
        return html+"<hr />";
    }

    private String parseEspecificacaoToHTML(EspecificacaoBean eb) {
        String html = "<tr><td>" + eb.getChave() + ":</td><td><input type='text' maxlength='50' size='50' "
                + "name='" + eb.getId() + "' id='" + eb.getId() + "' /></td></tr>";
        return html;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
